package com.aaa.project.commdetail.service.impl;

import com.aaa.project.commdetail.domain.TempTimeStatOnlineNew;
import com.aaa.project.commdetail.mapper.TempTimeStatOnlineNewMapper;
import com.aaa.project.commdetail.service.TempTimeStatOnlineNewService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author baibin
 * @version 1.0
 * @date 2025/4/23 15:15
 * @description TempTimeStatOnlineNewServiceImpl
 */
@Service
public class TempTimeStatOnlineNewServiceImpl implements TempTimeStatOnlineNewService {

    private static final Logger log = LoggerFactory.getLogger(TempTimeStatOnlineNewServiceImpl.class);

    @Resource
    private TempTimeStatOnlineNewMapper mapper;


    @Override
    public void add(TempTimeStatOnlineNew vo) {
        TempTimeStatOnlineNew oldVo = mapper.get(vo);
        if (oldVo == null) { // 新增
            mapper.insert(vo);
        } else { // 更新
            // 需要比较旧vo的96个字段和新vo的96个字段，旧vo字段值为1，则不用替换新vo字段值,否则就替换
            // 比较并更新 96 个字段
            for (int i = 1; i <= 96; i++) {
                String oldFieldValue = getFieldValue(oldVo, i); // 获取旧 vo 的字段值
                String newFieldValue = getFieldValue(vo, i);    // 获取新 vo 的字段值
                if (!"1".equals(oldFieldValue)) { // 如果旧字段值不为 1，则更新为新值
                    setFieldValue(oldVo, i, newFieldValue);
                }
            }
            mapper.update(oldVo); // 更新数据库
        }
    }


    /**
     * 获取指定字段的值
     */
    private String getFieldValue(TempTimeStatOnlineNew vo, int index) {
        try {
            java.lang.reflect.Field field = vo.getClass().getDeclaredField("online" + index);
            field.setAccessible(true);
            return (String) field.get(vo);
        } catch (Exception e) {
            log.error("获取字段值失败: online{}", index, e);
            return null;
        }
    }

    /**
     * 设置指定字段的值
     */
    private void setFieldValue(TempTimeStatOnlineNew vo, int index, String value) {
        try {
            java.lang.reflect.Field field = vo.getClass().getDeclaredField("online" + index);
            field.setAccessible(true);
            field.set(vo, value);
        } catch (Exception e) {
            log.error("设置字段值失败: online{}", index, e);
        }
    }
}
